/*
 * DialogHandler.java
 *
 */

package mvc.framework;

import java.io.PrintWriter;

import javax.servlet.http.*;
import javax.servlet.ServletContext;

/**
 * Classe per gestire le informazioni necessarie alla costruzione della risposta
 *
 * @author Grillo
 */
public class DialogHandler {
    private ServletContext context = null;
    private HttpServletRequest request = null;
    private HttpServletResponse response = null;
    private PrintWriter out = null;
            
    /**
     * 
     * Crea una nuova istanza di DialogHandler 
     * 
     * @param request la richiesta generata dall'utente
     * @param out il flusso per fornire l'output
     */
    public DialogHandler(HttpServletRequest request, HttpServletResponse response) 
            throws Exception {
        this(request, response, null);
    }

    public DialogHandler(HttpServletRequest request, 
            HttpServletResponse response, 
            ServletContext context) throws Exception {
        setRequest(request);
        setResponse(response);
        setContext(context);
        setOut(response.getWriter());
    }

    
    public ServletContext getContext() {
        return context;
    }
    
    public void setContext(ServletContext context) {
        this.context = context;
    }

    
    public HttpServletRequest getRequest() {
        return request;
    }
    
    public void setRequest(HttpServletRequest request) {
        this.request = request;
    }

    public String getParameter(String parameterName) {
        return this.request.getParameter(parameterName);
    }    
    
    public HttpServletResponse getResponse() {
        return response;
    }
    
    public void setResponse(HttpServletResponse response) {
        this.response = response;
    }

    public PrintWriter getOut() {
        return out;
    }
            
    private void setOut(PrintWriter out) {
        this.out = out;
    }

    public HttpSession getSession() {
        return request.getSession(true);
    }

    public Cookie[] getCookies() {
        return request.getCookies();
    }
    
    public Cookie getCookie(String cookieName) {
        Cookie[] cookies = getCookies();
        if (cookies == null) return null;    // Nessun cookie impostato

        // Analisi dell'elenco dei cookies della sessione
        for (int i = 0; i < cookies.length; i++) {
            if (cookies[i].getName().equalsIgnoreCase(cookieName)) {
                return cookies[i];
            }
        }
        return null;
    }
}